import React from 'react';
import upload from './upload';
import './index.css';

type FileUploadProps = {
    accept?: string;
    onSuccess?: Function;
    onError?: Function;
    onChange?: Function;
}

class FileUpload extends React.Component<Props & FileUploadProps, State> {
    static defaultProps = {
        accept: "image/*",
    }
    constructor(props) {
        super(props)

        this.state = {
            files: '',
        }
    }

    handleFileChange = () => {
        const fileSelectorEl: any = this.refs['file-upload-input'];
        if (fileSelectorEl && fileSelectorEl.files && fileSelectorEl.files.length) {
            var files = fileSelectorEl.files;
            this.props.onChange && this.props.onChange(files)
            upload(files[0]).then(url => {
                if (fileSelectorEl) {
                    fileSelectorEl.value = '';
                }
                this.props.onSuccess && this.props.onSuccess(url)
            }).catch(e => {
                this.props.onError && this.props.onError(e)
            })
        }
    } 

    render() {
        const { accept } = this.props;
        const { files } = this.state;
        return (
            <div className={`file-upload ${this.props.className}`}>
                {this.props.children}
                <input 
                    type="file" 
                    ref="file-upload-input"
                    value={files}
                    accept={accept || "image/*"}
                    onChange={this.handleFileChange}
                />
            </div>
        );
    }
}

export default FileUpload
